<template>
    <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }">
        <!-- <el-table-column prop="warehouse_Name" label="仓库名称" />
        <el-table-column prop="zone_Name" label="库区名称" />
        <el-table-column prop="location_Name" label="库位名称" /> -->
        <el-table-column prop="warehouse_Name" label="仓库">
            <template #default="{ row }">
                {{ warehouseNameMap[row.warehouse_Code] || '加载中...' }}
            </template>
        </el-table-column>
        <el-table-column prop="zone_Name" label="库区">
            <template #default="{ row }">
                {{ zoneNameMap[row.zone_Code] || '加载中...' }}
            </template>
        </el-table-column>
        <el-table-column prop="location_Name" label="库位">
            <template #default="{ row }">
                {{ locationNameMap[`${row.zone_Code}_${row.location_Code}`] || '加载中...' }}
            </template>
        </el-table-column>
        <el-table-column prop="stock_numder" label="当前库存" />
        <el-table-column prop="stock_planned_outbound_qty" label="预计出库" />
        <el-table-column prop="stock_planned_store_qty" label="预计入库" />
    </el-table>
    <div class="pagination-wrapper">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
            :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script>
import axios from 'axios'
import { ref, reactive, onMounted } from 'vue'
export default {
    props: {
        detailsData: {
            type: String,
            required: true
        },
        orderCode: String
    },
    setup(props) {
        const tableData = ref([])
        const measureOptios = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const warehouseNameMap = ref({})
        const zoneNameMap = ref({})
        const locationNameMap = ref({})

        onMounted(() => {
            fill()
            count()
        })

        function fill() {
            axios.get("http://localhost:5181/api/Db_warehouse/GetInv_Stock", {
                params: {
                    productName: props.detailsData,
                    currentPage: currentPage.value,
                    pageSize: pageSize.value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then(async (res) => {
                tableData.value = res.data

                console.info(res.data)
                var warehouse_code = ref('');
                // 仓库名称缓存
                const uniqueWarehouseCodes = [...new Set(res.data.map(r => r.warehouse_Code).filter(Boolean))]
                for (const code of uniqueWarehouseCodes) {
                    if (!warehouseNameMap.value[code]) {
                        const res = await axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBy_Select_Async_code", {
                            params: { warehouse_code: code },
                            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                        })
                        warehouseNameMap.value[code] = res.data?.[0]?.warehouse_name || '未知仓库'
                    }
                }

                // 库区名称缓存
                const uniqueZoneCodes = [...new Set(res.data.map(r => r.zone_Code).filter(Boolean))]
                for (const code of uniqueZoneCodes) {
                    if (!zoneNameMap.value[code]) {
                        const warehouseCode = res.data.find(r => r.zone_Code === code)?.warehouse_Code
                        if (!warehouseCode) {
                            zoneNameMap.value[code] = '未知库区'
                            continue
                        }

                        const zoneRes = await axios.get(
                            "http://localhost:5181/api/Db_warehouse_zone/Warehouse_zone_By_Select_Async_code",
                            {
                                params: {
                                    warehouse_code: warehouseCode,
                                    zone_code: code
                                },
                                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                            }
                        )
                        zoneNameMap.value[code] = zoneRes.data?.[0]?.zone_name || '未知库区'
                    }
                }

                // 库位名称缓存（需要 zone_code + location_code）
                const uniqueLocationKeys = [
                    ...new Set(
                        res.data
                            .filter(r => r.zone_Code && r.location_Code)
                            .map(r => `${r.zone_Code}_${r.location_Code}`)
                    )
                ]

                for (const key of uniqueLocationKeys) {
                    if (!locationNameMap.value[key]) {
                        const [zone_code, location_code] = key.split('_')
                        const res = await axios.get(
                            "http://localhost:5181/api/Db_warehouse_location/Warehouse_location_By_Select_Async_code",
                            {
                                params: { zone_code, location_code },
                                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                            }
                        )
                        locationNameMap.value[key] = res.data?.[0]?.location_name || '未知库位'
                    }
                }
            }).catch((err) => {
                console.info(err)
            });
        }

        function count() {
            axios.get("http://localhost:5181/api/Db_warehouse/Inv_StockCount", {
                params: {
                    productName: props.detailsData,
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            fill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            fill();
        }
        return {
            tableData, measureOptios, currentPage, pageSize, pageCount, handleCurrentChange, handleSizeChange, warehouseNameMap, zoneNameMap, locationNameMap
        }
    }
}
</script>

<style scoped>
.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    margin-top: 20px;
    /* 与表格的间距 */
}
</style>